package cn.cyl.pet.service.impl;

import cn.cyl.basic.exception.BusinessException;
import cn.cyl.basic.service.BaiduAiAuditService;
import cn.cyl.basic.service.impl.BaseServiceImpl;
import cn.cyl.basic.util.*;
import cn.cyl.order.domain.OrderPetAcquisition;
import cn.cyl.order.mapper.OrderPetAcquisitionMapper;
import cn.cyl.org.domain.Employee;
import cn.cyl.org.domain.Shop;
import cn.cyl.org.mapper.EmployeeMapper;
import cn.cyl.org.mapper.ShopMapper;
import cn.cyl.pet.domain.SearchMasterMsg;
import cn.cyl.pet.domain.SearchMasterMsgAuditLog;
import cn.cyl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.cyl.pet.mapper.SearchMasterMsgMapper;
import cn.cyl.pet.msgDto.MsgDto;
import cn.cyl.pet.query.SearchMasterMsgQuery;
import cn.cyl.pet.service.SearchMasterMsgService;
import cn.cyl.user.domain.Logininfo;
import cn.cyl.user.domain.User;
import cn.cyl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements SearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private BaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    /**
     * 发布寻主消息
     * @param searchMasterMsg
     * @param request
     * @return
     */
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核或驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //添加进数据库
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user=userMapper.loadByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);

        //百度审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if(boo1 && boo2){//审核通过
            //改状态
            searchMasterMsg.setState(1);

            //添加进审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            log.setNote("审核通过");
            searchMasterMsgAuditLogMapper.save(log);

            //获取离用户最近的店铺
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop!=null){//找到了最近的店铺
                searchMasterMsg.setShopId(nearestShop.getId());

                //SmsUtils.sendSms(nearestShop.getTel(),"你有新的订单，请前往"+searchMasterMsg.getAddress()+"处理");
                System.out.println("你有新的订单，请前往" + searchMasterMsg.getAddress() + "处理");
            }else {//没有找到最近的店铺
                searchMasterMsg.setState(3);//放进寻主池
                System.out.println("你附近暂时没店铺");
            }

            searchMasterMsgMapper.save(searchMasterMsg);
            return new AjaxResult();

        }else {//审核没有通过

            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setNote("审核失败");
            log.setState(0);
            log.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLogMapper.save(log);

            searchMasterMsgMapper.del(searchMasterMsg.getId());
            System.out.println("寻主消息发送失败");
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.setSuccess(false);
            ajaxResult.setMsg("寻主消息发送失败");
            return  ajaxResult;
        }
    }

    //管理员查询待处理的寻主消息 -----区分平台管理员还是店铺管理员
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee=employeeMapper.loadBylogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }
    //用户查询自己发布的寻主消息
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {

        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }
    //查询寻主池里面的寻主信息
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);
        return super.queryPage(query);
    }


    //管理员查询已经完成的寻主消息----业务要区分平台管理员还是店铺管理员
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee=employeeMapper.loadBylogininfoId(logininfo.getId());
        if(employee.getShop_id()!=null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }


    //拒单
    @Override
    public void reject(Long id) {
        //拒单后放入寻主池state=3，置空店铺id
        searchMasterMsgMapper.reject(id);
    }

    //接单
    @Override
    public void accept(MsgDto msgDto) {

       OrderPetAcquisition order=orderPetAcquisitionMapper.loadByMsgId(msgDto.getMsgId());
        if(order!=null && order.getState()==0){//有订单且当前订单是待处理
            throw new BusinessException("当前订单正在处理中，请勿重复接单");
        }
        //生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadOne(msgDto.getMsgId());
        OrderPetAcquisition newOrder=createOrder(msgDto,msg);
        orderPetAcquisitionMapper.save(newOrder);

        //发送短信
//        Employee employee = employeeMapper.loadOne(msgDto.getHandler());
//        SmsUtils.sendSms(employee.getPhone(),"你有新订单，请两天之内去"+msg.getAddress()+"接回宠物");
        System.out.println("你有新订单，请两天之内去"+msg.getAddress()+"接回宠物");
    }

    private OrderPetAcquisition createOrder(MsgDto msgDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getUserId()));
        order.setDigest(msgDto.getNote());
        //最后的确认时间
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        //order.setState(0); 实体类里默认是0不用写
        order.setPrice(msg.getPrice());
        //order.setPaytype(); 支付方式要等拿到宠物后再去设置
        //order.setPetId(); 宠物id要等拿到宠物后才去设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
}
